<?php


namespace app\cms\model;


use app\cms\community\lib\modelData;
use app\cms\community\lib\QueryModel;
use iflow\Response;
use think\facade\Db;

class formModel extends QueryModel
{

    protected $table = "form_table";

    public function getForm(int $form_id): ?array
    {
        $form = $this -> where([
            'form_id' => $form_id
        ])->findOrEmpty();

        if ($form->isEmpty()) return null;
        return $form->toArray();
    }

    public function getFormByFormName(string $form_name): ?array
    {
        $form = $this -> where([
            'form_name' => $form_name
        ])->findOrEmpty();

        if ($form->isEmpty()) return null;
        return $form->toArray();
    }

    public function getBindModelData(int $form_id, string $keyword = ""): Response
    {
        $form = $this->getForm($form_id);
        if ($form) {
            $bindForm = $this->getFormByFormName($form['form_bind_model']);
            if ($bindForm) {
                $query = Db::connect($this->connection) -> name($form['form_bind_model']);
                if ($bindForm['title_field'] !== '-1') {
                    $query->whereLike($bindForm['title_field'], "%{$keyword}%");
                }
                $query = $query->paginate([
                    'page' => request() -> getParams('page'),
                    'list_rows' => 10
                ]);
                $items = $query->items();
                return $items ?
                    message()->success('查询成功', $items, [
                        'count' => $query->total(),
                        'page' => $query->lastPage(),
                        'title_field' => $bindForm['title_field']
                    ]) : message()->nodata('暂无数据');
            }
        }
        return message()->nodata('暂无绑定模型');
    }

    public function addForm(string $formName = ''): Response
    {
        $sql = "
            create table `{$formName}` (
                %s
                key (`uuid`)
            ) ENGINE = innodb
            DEFAULT CHARSET = utf8mb4;
        ";

        $formField = config('formField');

        $field = "";
        $saveData = [];
        foreach ($formField as $key => $value) {
            $field .= "`{$key}` {$value['command']}, \r\n";
            $saveData[$key] = [
                'form_id' => '',
                'form_field_name' => $key,
                'form_field_type' => $value['type'],
                'form_field_length' => $value['length'],
                'form_field_description' => $value['desc'],
                'form_field_default' => $value['default'],
                'create_time' => time(),
                'update_time' => time()
            ];
        }
        $sql = str_replace("\r\n", "", sprintf($sql, $field));

        // 创建数据
        Db::connect($this->connection) -> execute($sql);
        $create = self::create([
            'form_name' => $formName
        ])->toArray();

        foreach ($saveData as $key => $value) {
            $saveData[$key]['form_id'] = $create['id'];
        }

        formFieldModel::insertAll($saveData);
        return message()->success('创建模型成功', $create);
    }

    // 删除自定义表模型
    public function delForm(int $form_id): Response
    {
        $form = $this -> where([
            'form_id' => $form_id
        ])->findOrEmpty();

        if ($form->isExists()) {
            Db::connect($this->connection) -> execute("drop table {$form['form_name']}");

            formFieldModel::where([
                'form_id' => $form_id
            ]) -> delete();

            $this -> where([
                'form_id' => $form_id
            ])->delete();
            return message()->success('表模型删除成功');
        }
        return message()->nodata('表模型不存在');
    }

    // 查询自定义表
    public function getHasModelDataList($form_id, $groupId = '', $id = '', $user_id = '', array $options = [
        'order' => 'desc',
        'pageSize' => 15,
        'keyword' => ''
    ]): Response
    {
        try {
            $modeData = new modelData();
            return $modeData -> setFormId($form_id)
                -> setGroupId($groupId)
                -> setId($id)
                -> setUserId($user_id)
                -> setOptions($options)
                -> query();
        } catch (\Exception $exception) {
            return message() -> parameter_error($exception -> getMessage());
        }
    }

    /**
     * 获取指定模型上一条和下一条数据
     * @param int $form_id
     * @param string|int $groupId
     * @param int $offset
     * @return Response
     */
    public function getPreAndNext(int $form_id, string|int $groupId = "", int $offset = 0): Response {

        $pre = [];

        $options = [ 'offset' => $offset - 1, 'limit' => 1 ];

        // 如果id 大于一 才获取上一页数据
        if ($offset > 1) {
            $pre = $this -> getHasModelDataList($form_id, $groupId, options: $options) -> data['items'][0] ?? [];
        }

        // 获取下一条数据
        $options['offset'] = $offset + 1;
        $next = $this -> getHasModelDataList($form_id, $groupId, options: $options) -> data['items'][0] ?? [];

        return message() -> success('查询成功', [
            'pre' => $pre,
            'next' => $next
        ]);
    }
}